package com.spider.silence.pool;

import com.google.common.collect.Lists;
import com.spider.silence.downloader.YiBinZeroJuLiDownLoader;
import com.spider.silence.utils.PropertiesUtil;
import org.apache.log4j.Logger;

import java.util.LinkedList;

/**
 * Created by qiuhao on 2017/3/28.
 */
public class YiBinZeroJuLiLoaderPool {
    private Logger logger = Logger.getLogger(ChengduLifeDownLoaderPool.class);
                private static YiBinZeroJuLiLoaderPool instance=new YiBinZeroJuLiLoaderPool();
                protected LinkedList<YiBinZeroJuLiDownLoader> pool = Lists.newLinkedList();
    private YiBinZeroJuLiLoaderPool(){
                    int initNum= Integer.parseInt(PropertiesUtil.getVal("YiBinZeroJuLi.DownLoader.Pool.initNum"));
                    for(int i=0;i<initNum;i++){
                        YiBinZeroJuLiDownLoader downLoader =new YiBinZeroJuLiDownLoader();
                        downLoader.init();
                        pool.add(downLoader);
                    }
                }
            public  static YiBinZeroJuLiLoaderPool getInstance(){
                return  instance;
            }
            public  void releaseDownLoader(YiBinZeroJuLiDownLoader downloader) {
                if (downloader != null) {
                    synchronized (pool) {
                        pool.addLast(downloader);
                pool.notifyAll();
            }
        }
    }
    public YiBinZeroJuLiDownLoader fetchDownLoader(long mills) throws InterruptedException {
        synchronized (pool){
            if(mills<=0){
                while (pool.isEmpty()){
                    pool.wait();
                }
                return pool.removeFirst();
            }else {
                long future= System.currentTimeMillis()+mills;
                long remianing=mills;
                while (pool.isEmpty() && remianing >0){
                    pool.wait(remianing);
                    remianing=future-System.currentTimeMillis();
                }
                YiBinZeroJuLiDownLoader downLoader =null;
                if(!pool.isEmpty()){
                    downLoader=pool.removeFirst();
                }
                return downLoader;
            }
        }
    }
    /**
     * 清空池
     */
    public void empty(){
        pool= Lists.newLinkedList();
    }

}
